package biz.datalk.industrialland.common.validated;

import biz.datalk.industrialland.common.result.UnifyResult;
import biz.datalk.industrialland.common.util.I18NUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author tarofang@163.com
 * @date 2019-12-17
 */
@Component
public class ValidateHelper {

    private final Validator validator;


    @Autowired
    public ValidateHelper(Validator validator) {
        this.validator = validator;
    }

    public <T> UnifyResult validate(T object, Class<?>... groups) {
        Set<ConstraintViolation<T>> set = validator.validate(object, groups);
        if (CollectionUtils.isEmpty(set)) {
            return UnifyResult.success();
        }

        String msg = "";
        for (ConstraintViolation<T> violation : set) {
            // ConstraintDescriptor<?> constraintDescriptor = violation.getConstraintDescriptor();
            String message = violation.getMessage();
            if (StringUtils.startsWith(message, "{") && StringUtils.endsWith(message, "}")) {
                message = message.replace("{", "");
                message = message.replace("}", "");
                msg = I18NUtil.getMsg(message);
            } else {
                msg = message;
            }
            break;
        }

        return UnifyResult.fail(msg);
    }
}
